package com.jsbb.util;

import com.jsbb.core.Const;
import com.jsbb.core.UserToken;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Base64;
import java.util.Optional;

/**
 * @author jsbb
 */
public class TokenUtils {

    public static String createToken(Long id) {
        UserToken userToken = new UserToken();
        userToken.setId(id);
        userToken.setTimestamp(System.currentTimeMillis());
        return Base64.getEncoder().encodeToString(JsonUtils.toJsonString(userToken).getBytes());
    }

    public static Long getUserId(HttpServletRequest request) {
        try {
            String token = Optional.ofNullable(request.getHeader(Const.TOKEN)).orElse((String) request.getAttribute(Const.TOKEN));
            if (token == null) {
                return null;
            }
            UserToken userToken = JsonUtils.toBean(new String(Base64.getDecoder().decode(token)), UserToken.class);
            if (userToken == null) {
                return null;
            }
            return userToken.getId();
        } catch (Exception e) {
            return null;
        }
    }
}
